package jwebtest.queue;

/**
 * 队列数组实现： 队列长度有限，但是考虑到平时一般都使用有界队列，这应该也不算是个缺点 插入和删除的时间复杂度都为O(1)
 * 
 * @author Yuaaqy
 *
 */
public class ArrayQueue<T> {
	private T[] objs;
	private int first;
	private int last;
	private int size;

	public ArrayQueue(int size) {
		objs = (T[]) new Object[size];
		this.first = 0;
		this.last = -1;
		this.size = 0;
	}

	public void push(T obj) throws Exception {
		if (this.size > objs.length)
			throw new Exception("Queue is full!");
		if (last == objs.length - 1)
			last = -1;
		objs[++last] = obj;
		size++;
	}

	public T pop() throws Exception {
		if (this.size == 0)
			throw new Exception("Queue is empty!");
		T tmp = objs[first++];
		objs[first - 1] = null;
		if (first == objs.length)
			first = 0;
		size--;
		return tmp;
	}

	public T peek() throws Exception {
		if (this.size == 0)
			throw new Exception("Queue is empty!");
		return objs[first];
	}

	public int size() {
		return this.size;
	}

	public boolean isEmpty() {
		return (size == 0);
	}

	public boolean isFull() {
		return (size == objs.length);
	}

	public void display() {
		System.out.print("first -> last : | ");
		for (int i = 0; i < objs.length; i++) {
			System.out.print(objs[i] + " | ");
		}
		System.out.println("");
	}
}
